<?php
namespace Api\Controller;
use Think\Controller\RestController;
use Think\Controller;
header("content-type:application/json;charset=utf-8");
header("Access-Control-Allow-Origin:*");
class LoginController extends RestController
{

    //初始化
    function _initialize() {
         //清除过期验证码
         $verification_code = M("verification_code");
         $wher2=[];
         $wher2['times']=['lt',time()];
         $verification_code->where($wher2)->delete();
    }
    //业务员列表
    public function yewyw_lsit(){
        $admin = M("admin");
        $user = M("user");
        $detail = I('post.');
        $where['atype']=1;
        $uid=$detail['uid'];
        if($uid){
            $yw_id=$user->where(['uid'=>$uid])->getField('yw_id');
            if($yw_id){
                $where['aId']=$yw_id;
            }else{
                $data['code']=0;
                $data['msg']='该账号没绑定业务员';
                exit(json_encode($data));
            }
        }
        $list = $admin->where($where)->field('aId,aName')->order('aId asc')->select();
        $data['code']=200;
        $data['msg']='查询成功';
        $data['data']['list']=$list;
        exit(json_encode($data));
    }
    public function Systemcc()
    {
        $systemInfo = M("system");
        $rs_systemInfo = $systemInfo->where("sId=1")->find();
        $data['code']=200;
        $data['msg']='查询成功';
        $data['data']['info']=$rs_systemInfo;
        exit(json_encode($data));
    }
    //登录检查(管理员)
    public function checklogin()
    {
        $u = D('Admin');
       
        //登录验证
        $post = I('post.');
        $system = M("system");
        $rs_system = $system->field("sCheckCodeSwitch,sErrorPwdLockNum,sLoginTimeout,order_contral")->where("sId=1")->find(); 
        if (!$post['aUser']) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '用户名必须'), 'JSON');
        }
        if (!$post['aPwd']) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '密码必须！'), 'JSON');
        }
        if($rs_system["sCheckCodeSwitch"] == 1) {
            $verification = M("verification_code");
            $code_info=$verification->where(['codes_name'=>$post['code']])->find();
            if (empty($code_info)) {
                $data['code']=0;
                $data['msg']='验证码错误！';
                exit(json_encode($data));
            }
            if(time()>$code_info['times']){
                $data['code']=0;
                $data['msg']='验证码已过期！';
                exit(json_encode($data));
            }
        }
        $form = $post['form'] && $post['form'] < 4 ? $post['form'] : 1;
        $user = $u->login($form, $post);
        // 不存在此用户
        if (!$user) {
            $this->ajaxReturn(array('code' => 0, 'msg' => $u->getError()));
        }
        unset($user['password']);
        //查看是否登录成功更新最后一次登录信息
        if ($user) { //如果设置了用户微信信息，就清除微信信息
            //如果之前没有链接，就跳转到用户中心
            $admin['token'] = $user['token'];
            $admin['atype'] = $user['atype'];
            $admin['aName'] = $user['aName'];
            $admin['authority'] = $user['authority'];
            $admin['qx_list'] = $user['qx_list'];
            $admin['order_contral'] =$rs_system['order_contral'];  
            if($user['authority']=="ALL"){
                $admin['qxlsit']= $this->getadx_cc();
            }else{
                //检测账号是否拥有了自己的独立权限
                if($user['qx_list']){
                    $admin['qxlsit']= $this->getadxc($user['qx_list']);
                }else{
                    $admin['qxlsit']= $this->getadx($user['atype']);
                }
                
            }
            //登录成功删除验证码
            $verification->where(['codes_name'=>$post['code']])->delete();
            $admin['avatar'] = $user['avatar'] ?: 'https://wages-zymaimai.oss-cn-beijing.aliyuncs.com/2023/03/02/6400606a88a09.jpg';
            $this->ajaxReturn(array('code' => 200, 'msg' => '登录成功', 'data' => $admin), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '登录失败，请稍后重试'), 'JSON');
        }
    }
 
    
    public function cc(){
        $sdaf=$this->getadx(0);
        
        $data_cc['data']['list']=$sdaf;
	    exit(json_encode($data_cc));
    }
    function getadx($atype){
        $roles = M('roles');
        $model = M('roles_menu');
        $info=$roles->where(['atype'=>$atype])->find();
        $action_list=$info['action_list'];
        $ac_lst=explode(',',$action_list);
        $list=[];
        $list=$model->where(['pid'=>0])->field('id,names,sort')->order('sort asc')->select();
        if($list){
            foreach($list as $k=>$val){
               $list2= $model->where(['pid'=>$val['id']])->field('id,names,sort')->order('sort asc')->select();
               if($list2){
                    foreach($list2 as $k2=>$vals){
                          if(!in_array($vals['id'],$ac_lst)){
                              unset($list2[$k2]);
                          } 
                    }
               }
               if($list2){
                  $list[$k]['list2']=array_values($list2);
               }else{
                    if($val['id']<>1){
                        unset($list[$k]);
                    }
               }
               
            }
      }
       $mtc=array_values($list);
       return $mtc;
    }
    function getadxc($aztype){
        $roles = M('roles');
        $model = M('roles_menu');
        $ac_lst=explode(',',$aztype);
        $list=[];
        $list=$model->where(['pid'=>0])->field('id,names,sort')->order('sort asc')->select();
        if($list){
            foreach($list as $k=>$val){
               $list2= $model->where(['pid'=>$val['id']])->field('id,names,sort')->order('sort asc')->select();
               if($list2){
                    foreach($list2 as $k2=>$vals){
                          if(!in_array($vals['id'],$ac_lst)){
                              unset($list2[$k2]);
                          } 
                    }
               }
               if($list2){
                  $list[$k]['list2']=array_values($list2);
               }else{
                    if($val['id']<>1){
                        unset($list[$k]);
                    }
               }
               
            }
      }
       $mtc=array_values($list);
       return $mtc;
    }
    

    //超级管理员A
    function getadx_cc(){
        $roles = M('roles');
        $model = M('roles_menu');
        $list=[];
        $list=$model->where(['pid'=>0])->field('id,names,sort')->order('sort asc')->select();
        if($list){
            foreach($list as $k=>$val){
               $list2= $model->where(['pid'=>$val['id']])->field('id,names,sort')->order('sort asc')->select();
               $list[$k]['list2']=$list2;
            }
        }
        return $list;
    }
    
    //登录检查(客户,员工)
    public function uchecklogin()
    {
        $u = D('User');
        //登录验证
        $post = I('post.');
        $form = $post['form'] && $post['form'] < 4 ? $post['form'] : 1;
        $system = M("system");
        $rs_system = $system->field("sCheckCodeSwitch,sErrorPwdLockNum,sLoginTimeout,order_contral")->where("sId=1")->find(); 
        if (!$post['aUser']) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '用户名必须'), 'JSON');
        }
        if (!$post['aPwd']) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '密码必须！'), 'JSON');
        }
        
        if($rs_system["sCheckCodeSwitch"] == 1) {
            $verification = M("verification_code");
            $code_info=$verification->where(['codes_name'=>$post['code']])->find();
            if (empty($code_info)) {
                $data['code']=0;
                $data['msg']='验证码错误！';
                exit(json_encode($data));
            }
            if(time()>$code_info['times']){
                $data['code']=0;
                $data['msg']='验证码已过期！';
                exit(json_encode($data));
            }
        }
      
        $user = $u->login($form, $post);
        // 不存在此用户
        if (!$user) {
            $this->ajaxReturn(array('code' => 0, 'msg' => $u->getError()));
        }
        unset($user['password']);
        //查看是否登录成功更新最后一次登录信息
        if ($user) { //如果设置了用户微信信息，就清除微信信息
            //如果之前没有链接，就跳转到用户中心
            $admin['token'] = $user['token'];
            $admin['types'] = $user['types'];
            $admin['names'] = $user['names'];
            $admin['order_contral'] =$rs_system['order_contral'];  
            $admin['avatar'] = $user['avatar'] ?: 'https://wages-zymaimai.oss-cn-beijing.aliyuncs.com/2023/03/02/640060c849864.jpg';
            $r_model = M('Roles');
            $stype = $admin['types'];
            //检测账号是否拥有了自己的独立权限
            $qx_list = $this->ugetadx(100,$stype);
            $admin['qxlsit']= $qx_list;
            //dump($admin);exit;
            $this->ajaxReturn(array('code' => 200, 'msg' => '登录成功', 'data' => $admin), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '登录失败，请稍后重试'), 'JSON');
        }
    }

    //user表权限
    function ugetadx($atype,$stype){
        $roles = M('roles');
        $model = M('roles_menu');
        $info=$roles->where(['atype'=>$atype,'stype'=>$stype])->find();
        $action_list = $info['action_list'];
        $ac_lst = explode(',',$action_list);
        $list=[];
        $list=$model->where(['pid'=>0])->field('id,names,sort')->order('sort asc')->select();
        if($list){
            foreach($list as $k=>$val){
               $list2= $model->where(['pid'=>$val['id']])->field('id,names,sort')->order('sort asc')->select();
               if($list2){
                    foreach($list2 as $k2=>$vals){
                          if(!in_array($vals['id'],$ac_lst)){
                              unset($list2[$k2]);
                          } 
                    }
               }
               if($list2){
                  $list[$k]['list2']=array_values($list2);
               }else{
                    if($val['id']<>1){
                        unset($list[$k]);
                    }
               }
               
            }
      }
       $mtc=array_values($list);
       return $mtc;
    }

    //退出登录
    public function Login_out(){
        $detail = I('post.');
        $token=$detail['token'];
        $token_model= M("token");
        $info=$token_model->where(['token'=>$token])->find();
        if($info){
           $result=$token_model->where(['token'=>$token])->delete();
           if($result){
                $data_cc['code'] =200;
                $data_cc['msg'] = "退出成功";
                $data_cc['data'] =$result;
                exit(json_encode($data_cc));
           }else{
                $data_cc['code'] = 0;
                $data_cc['msg'] = "操作失败";
                exit(json_encode($data_cc));
           }
        }else{
            $data_cc['code'] = 101;
            $data_cc['msg'] = "token不存在";
            exit(json_encode($data_cc));
        }
 
    }
    //修改密码
    public function uppwd(){
        $detail = I('post.');
        $token=$detail['token'];
        $aOldPwd = $detail["aOldPwd"];
        $aNewPwd = $detail["aNewPwd"];
        $token_model= M("token");
        $admin_model= M("admin");
        if($aOldPwd == null) {
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入旧密码";
            exit(json_encode($data_cc));
        }
        if($aNewPwd == null) {
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入新密码";
            exit(json_encode($data_cc));
        }
        $info=$token_model->where(['token'=>$token])->find();
        if($info){
            $aId= $info['aId'];
            $aOldPwdMd5 = md5($aOldPwd);
            $rs_pwd = $admin_model->where("aId=$aId")->field("aPwd")->find();
            if ($aOldPwdMd5 != $rs_pwd["aPwd"]) {
                $data_cc['code'] = 0;
                $data_cc['msg'] = "原密码错误";
                exit(json_encode($data_cc));
            }
            $data["aPwd"] = md5($aNewPwd);
           if($data["aPwd"]==$aOldPwdMd5){
                $data_cc['code'] = 0;
                $data_cc['msg'] = "原密码和新密码一致,无法修改。";
                exit(json_encode($data_cc));
           }
            $result = $admin_model->where("aId=$aId")->save($data);
            if($result) {
                //删除token 重新登录
                $token_model->where(['token'=>$token])->delete();
                $data_cc['code'] = 200;
                $data_cc['msg'] = "密码修改成功";
                $data_cc['data'] = $aId;
                exit(json_encode($data_cc));
            } else {
                $data_cc['code'] = 0;
                $data_cc['msg'] = "密码修改失败";
                exit(json_encode($data_cc));
            }
          
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "token不存在";
            exit(json_encode($data_cc));
        }
    }
    
    //更换头像功能
    public function change_avatar(){
        $detail = I('post.');
        $token=$detail['token'];
        $pircture=$detail['pircture'];
       
        $token_model= M("token");
        $info=$token_model->where(['token'=>$token])->find();
        if($info){
            $type=$info['type'];
            $aId= $info['aId'];
            if($type==1){
                $admin_model= M("admin");
                $where['aId']=$aId;
            }else{
                $admin_model= M("user");
                $where['uid']=$aId;
            }
            if(empty($pircture)){
                $data_cc['code'] = 0;
                $data_cc['msg'] = "请上传头像";
                exit(json_encode($data_cc));
            }
            $data['avatar']=$pircture;
            $result = $admin_model->where($where)->save($data);
            if($result) {
                $data_cc['code'] = 200;
                $data_cc['msg'] = "头像更新成功";
                $data_cc['data'] = $result;
                exit(json_encode($data_cc));
            } else {
                $data_cc['code'] = 0;
                $data_cc['msg'] = "头像更新失败";
                exit(json_encode($data_cc));
            }
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "token不存在";
            exit(json_encode($data_cc));
        }
    }
    

    // 用户注册
    public function register(){ 
        $user=D("User");
        $detail = I('post.');
        $system = M("system");
        $data = [];
        $data['username'] = trim($detail['username']);
        $data['names'] = trim($detail['names']);
        $data['password'] = $detail['password'];
        $data['company'] = $detail['company'];
        $data['mobile'] = $detail['mobile'];
        $data['address'] = $detail['address'];
        $data['avatar'] = 'https://wages-zymaimai.oss-cn-beijing.aliyuncs.com/2023/03/29/6423aafa356d3.jpg';
        if(empty($data['username'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入账号';
            exit(json_encode($data_cc));
        }
        $u_name=$user->where(['username'=>$data['username']])->count();
        $moble_c=$user->where(['mobile'=>$data['mobile']])->count();
        if($u_name){
            $data_cc['code']=0;
            $data_cc['msg']='该用户已注册了';
            exit(json_encode($data));
        }
        if(empty($data['names'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入真实姓名';
            exit(json_encode($data_cc));
        }
        if(empty($data['password'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入密码';
            exit(json_encode($data_cc));
        }
        if(empty($data['company'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入公司名称';
            exit(json_encode($data_cc));
        }
        if(empty($data['mobile'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入手机号码';
            exit(json_encode($data_cc));
        }
        if($moble_c){
            $data_cc['code']=0;
            $data_cc['msg']='该手机号已注册了';
            exit(json_encode($data_cc));
        }
        if(empty($data['address'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入收货地址';
            exit(json_encode($data_cc));
        }
        if(empty($detail['code'])){
            $data_cc['code']=0;
            $data_cc['msg']='请输入验证码';
            exit(json_encode($data_cc));
        }
        $rs_system = $system->field("sCheckCodeSwitch,sErrorPwdLockNum,sLoginTimeout")->where("sId=1")->find();
        if ($rs_system["sCheckCodeSwitch"] == 1) {
            $verification = M("verification_code");
            $code_info=$verification->where(['codes_name'=>$detail['code']])->find();
            if (empty($code_info)) {
                $data_cc['code']=0;
                $data_cc['msg']='验证码错误！';
                exit(json_encode($data_cc));
            }
            if(time()>$code_info['times']){
                $data_cc['code']=0;
                $data_cc['msg']='验证码已过期！';
                exit(json_encode($data_cc));
            }
        }
        unset($data['code']);
        $result = $this->khregister($data);
        if ($result) {
            $data_cc['code']=200;
            $data_cc['msg']='注册成功，请等待管理员审核。';
            exit(json_encode($data_cc));
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '注册失败'), 'JSON');
        }
    }
    public function  Verify(){
        $data_cc['code'] = 200;
        $data_cc['msg'] = '查询成功';
        $data_cc['data']['image_code'] = $this->getCode(4,60,20);
        exit(json_encode($data_cc));
    }

    //获取登录后的详情
    public function get_login(){
        $detail = I('post.');
        $token=$detail['token'];
        $token_model=M("token");
        $admin_model=M("admin");
        $user_model=M("user");
        $info=$token_model->where(['token'=>$token])->find();
        if($info){
            $type=$info['type'];
            if($type==1){
                $aId=$info['aId'];
                $u_info=$admin_model->where(['aId'=>$aId])->field('aId,aName,atype,atype,login_time,avatar')->find();
                $u_info['login_times']=date('Y-m-d H:i:s',$u_info['login_time']);
                if(empty($u_info['avatar'])){
                    $u_info['avatar']='https://wages-zymaimai.oss-cn-beijing.aliyuncs.com/2023/03/29/6423aafa356d3.jpg';
                }
            }else{
                $aId=$info['aId'];
                $u_info=$user_model->where(['uid'=>$aId])->field('uid,customer_no,username,company,names as aName,avatar,login_time')->find();
                $u_info['login_times']=date('Y-m-d H:i:s',$u_info['login_time']);
                $u_info['login_times']=date('Y-m-d H:i:s',$u_info['login_time']);
                if(empty($u_info['avatar'])){
                    $u_info['avatar']='https://wages-zymaimai.oss-cn-beijing.aliyuncs.com/2023/03/29/6423aafa356d3.jpg';
                }
            }
            $data_cc['code'] = 200;
            $data_cc['msg'] = '查询成功';
            $data_cc['data']['image_code'] =$u_info;
            exit(json_encode($data_cc));
        }else{
            $data['code']=101;
            $data['msg']='token验证失败';
            exit(json_encode($data));
        }
    }
    //验证码生产
    function getCode() {				 
        header('Content-type: image/gif');						//输出头信息
        $image_w=76;											//验证码图形的宽				
        $image_h=30;											//验证码图形的高
        $number=range(0,9);										//定义一个成员为数字的数组
        $character=range("Z","A");								//定义一个成员为大写字母的数组
        $result=$number; 			 
        $string="";												//初始化
        $len=count($result);									//新数组的长
        for($i=0;$i<4;$i++)
        {
            $new_number[$i]=$result[rand(0,$len-1)];			//在$result数组中随机取出6个字符
            $string=$string.$new_number[$i];					//生成验证码字符串
        }
        $verification = M("verification_code");
        $data['codes_name']=$string;
        $data['times']=time()+120;
        $result = $verification->add($data);  
        $check_image=imagecreatetruecolor($image_w,$image_h);	//创建图片对象
        $white=imagecolorallocate($check_image, 255, 255, 255);	
        $black=imagecolorallocate($check_image, 0, 0, 0);	
        imagefill($check_image,0,0,$white);//设置背景颜色为白色
        $line_color=imagecolorallocate($check_image, 255, 0, 0);//设直线的颜色
        imageline($check_image, 0, 10, 100,20, $line_color);//画线
        // for($i=0;$i<100;$i++)			 //加入100个干扰的黑点
        // {
        //     imagesetpixel($check_image, rand(0,$image_w), rand(0,$image_h),$black);
        // }
        for($i=0;$i<count($new_number);$i++)					//在背景图片中循环输出4位验证码
        {
            $x=mt_rand(1,7)+$image_w*$i/6;						//设定字符所在位置X坐标
            $y=mt_rand(1,$image_h/6);							//设定字符所在位置Y坐标
            //随机设定字符颜色
            $color=imagecolorallocate($check_image,mt_rand(0,200),mt_rand(0,200),mt_rand(0,200));
            //输入字符到图片中
            imagestring($check_image,5,$x,$y,$new_number[$i],$color);
        }
        imagepng($check_image);
        imagedestroy($check_image);
    }

      /**
     * 客户注册
     */
    function khregister($data){
        $salt= $this->GetRandStr(6);
        //客户编号
        $user = M("user");
        $num = $user->where(['types'=>0])->count();
        $data['customer_no'] = str_pad($num,6,"0",STR_PAD_LEFT);
        $data['issh'] = 0;
        $data['salt']=$salt;
        $data['types']=0;
        $data['status'] = 1;
        $data['password']=$this->getEncryptPassword($data['password'] ,$salt);
        $data['addtime']=date("Y-m-d H:i:s");
        return $user->add($data);
    }
    function GetRandStr($length){
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $rands= substr($randStr,0,$length);//substr(string,start,length);返回字符串的一部分
        return $rands;
    }

    function getEncryptPassword($password, $salt = ''){
        return md5(md5($password) . $salt);
    }
}
